package com.easy.orm.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.easy.orm.jdbc.transactional.TransactionalOperationsInterface;

/**
 * 
 * <b> jdbc 操作基类 </b>
 * 
 * 
 * @author kun
 * @see com.easy.orm.jdbc.transactional.TransactionalOperationsInterface
 */
public class JdbcOperations implements TransactionalOperationsInterface {

	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(JdbcOperations.class);

	/**
	 * 数据库连接池
	 */
	private DataSource dataSource;

	/**
	 * 数据连接
	 */
	private Connection transactionalConnection;

	/**
	 * 事务连接自动提交
	 */
	private boolean transactionalAutoCommit = true;

	/**
	 * <b>默认初始化实例</b>
	 */
	public JdbcOperations() {
		super();
	}

	/**
	 * <b>事务-初始化实例</b>
	 * 
	 * @param transactionalConnection 事务连接 {@link java.sql.Connection}
	 */
	public JdbcOperations(Connection transactionalConnection) {
		super();
		this.transactionalConnection = transactionalConnection;
		try {
			// 设置事务为 非自动提交
			this.transactionalAutoCommit = this.transactionalConnection.getAutoCommit();
			this.transactionalConnection.setAutoCommit(false);
		} catch (SQLException e) {
			LOGGER.error("set transatcional connection auto commit to false exception {}", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * <b>带数据源-初始化实例</b>
	 * 
	 * @param dataSource 数据库连接池 {@link javax.sql.DataSource}
	 */
	public JdbcOperations(DataSource dataSource) {
		super();
		this.dataSource = dataSource;
	}

	/**
	 * 获取数据库连接池
	 * 
	 * @return 数据库连接池 {@link javax.sql.DataSource}
	 */
	public DataSource getDataSource() {
		return dataSource;
	}

	/**
	 * 设置数据连接池
	 * 
	 * @param dataSource 数据连接池 {@link javax.sql.DataSource}
	 */
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	/**
	 * 查询 对象
	 * 
	 * @param sql 查询SQL {@link java.lang.String}
	 * @param params 查询参数
	 * @param paramsMapper 参数处理 {@link com.easy.orm.jdbc.ParamsMapper}
	 * @param resultSetExtractor 结果集处理 {@link com.easy.orm.jdbc.ResultSetExtractor}
	 * @return 结果集 {@link com.easy.orm.jdbc.ResultSetExtractor}
	 * @param <T> 返回数据类型
	 * @param <P> 参数数据类型
	 */
	public <T, P> T queryForObject(String sql, P params, ParamsMapper<P> paramsMapper,
			ResultSetExtractor<T> resultSetExtractor) {

		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		T result = null;

		try {
			// 获取连接
			connection = getConnection();
			// 执行查询
			preparedStatement = connection.prepareStatement(sql);
			paramsMapper.setParams(preparedStatement, params);
			resultSet = preparedStatement.executeQuery();
			// 整理返回结果 并 关闭数据库相关操作
			result = resultSetExtractor.extractData(resultSet);

		} catch (SQLException e) {
			// 查询异常
			LOGGER.error("query error SQL[{}] exception [{}]", sql, e);
			throw new RuntimeException(e);
		} finally {
			try {
				// 关闭
				close(connection, preparedStatement, resultSet, connection.getAutoCommit());
			} catch (SQLException e) {
				LOGGER.error("close exception [{}]", e);
				throw new RuntimeException(e);
			}
		}

		return result;
	}

	/**
	 * 修改语句
	 * 
	 * @param sql sql {@link java.lang.String}
	 * @param params 参数
	 * @param paramsMapper 参数处理 {@link com.easy.orm.jdbc.ParamsMapper}
	 * @return SQL结果 {@link java.sql.Statement#executeUpdate(String)}
	 * @param <P> 参数数据类型
	 */
	public <P> int update(String sql, P params, ParamsMapper<P> paramsMapper) {

		Connection connection = null;
		boolean historyAutoCommit = true;
		PreparedStatement preparedStatement = null;
		int result = -1;

		try {
			// 获取连接
			connection = getConnection();
			historyAutoCommit = connection.getAutoCommit();
			connection.setAutoCommit(false);
			// 执行查询
			preparedStatement = connection.prepareStatement(sql);
			paramsMapper.setParams(preparedStatement, params);
			result = preparedStatement.executeUpdate();
			// 提交事务
			commit(connection);

		} catch (SQLException e) {
			// 执行错误 回滚事务
			LOGGER.error("update error SQL[{}] exception [{}]", sql, e);
			rollback(connection, sql, e);
			throw new RuntimeException(e);

		} finally {
			try {
				// 关闭
				close(connection, preparedStatement, null, historyAutoCommit);
			} catch (SQLException e) {
				LOGGER.error("close exception [{}]", e);
				throw new RuntimeException(e);
			}

		}

		return result;
	}

	/**
	 * 批量处理
	 * 
	 * @param sql sql {@link java.lang.String}
	 * @param params params
	 * @param paramsMapper 参数处理 {@link com.easy.orm.jdbc.ParamsMapper}
	 * @return 修改结果 {@link java.sql.Statement#executeBatch()}
	 * @param <P> 参数数据类型
	 */
	public <P> int[] batch(String sql, List<P> params, ParamsMapper<P> paramsMapper) {

		Connection connection = null;
		boolean historyAutoCommit = true;
		PreparedStatement preparedStatement = null;
		int[] result = null;

		try {
			// 获取连接
			connection = getConnection();
			historyAutoCommit = connection.getAutoCommit();
			connection.setAutoCommit(false);
			// 执行处理
			preparedStatement = connection.prepareStatement(sql);
			for (int index = 0; index < params.size(); index++) {
				paramsMapper.setParams(preparedStatement, params.get(index));
				preparedStatement.addBatch();
			}
			result = preparedStatement.executeBatch();
			preparedStatement.clearBatch();

			// 提交事务
			commit(connection);
		} catch (SQLException e) {
			// 批量处理错误 事务回滚
			LOGGER.error("batch error SQL[{}] exception [{}]", sql, e);
			rollback(connection, sql, e);
			throw new RuntimeException(e);
		} finally {
			try {
				// 关闭
				close(connection, preparedStatement, null, historyAutoCommit);
			} catch (SQLException e) {
				LOGGER.error("close exception [{}]", e);
				throw new RuntimeException(e);
			}
		}

		return result;
	}

	/**
	 * 获取数据库 连接
	 * 
	 * @return 数据库连接
	 * 
	 * @throws SQLException sql 异常
	 */
	public Connection getConnection() throws SQLException {
		return this.transactionalConnection != null ? this.transactionalConnection : dataSource.getConnection();
	}

	/**
	 * 事务提交
	 * 
	 * @throws SQLException 事务提交异常
	 */
	public void commit() throws SQLException {
		this.transactionalConnection.commit();
	}

	/**
	 * 事务提交
	 * 
	 * @throws SQLException 事务提交异常
	 */
	private void commit(Connection connection) throws SQLException {
		// 提交事务
		if ((transactionalConnection == null && !connection.getAutoCommit())) {
			connection.commit();
		}
	}

	/**
	 * 回滚事务
	 * 
	 * @throws SQLException 回滚异常
	 */
	public void rollback() throws SQLException {
		this.transactionalConnection.rollback();
	}

	/**
	 * 事务回滚
	 * 
	 * @param connection 连接
	 * @param sql 回滚sql
	 * @param e 异常
	 */
	private void rollback(Connection connection, String sql, Exception e) {
		try {

			// 1、不是全局事务 2、设置为非自动提交
			if (transactionalConnection == null && !connection.getAutoCommit()) {
				// 当前连接 事务回滚
				connection.rollback();
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("batch error rollback! SQL [{}]  ExcePtion [{}]", sql, e);
				}
			}
		} catch (SQLException rollbackException) {
			// 回滚异常
			LOGGER.debug("batch  rollback error! SQL [{}]  ExcePtion [{}]", sql, e);
			throw new RuntimeException(rollbackException);
		}
	}

	/**
	 * 关闭事务连接
	 * 
	 * @throws SQLException 关闭异常
	 */
	public void close() throws SQLException {
		if (transactionalConnection != null) {
			// 提交剩余 事务
			commit();
		}

		// 关闭事务连接
		close(transactionalConnection, null, null, transactionalAutoCommit);

		// 销毁连接
		transactionalConnection = null;
	}

	/**
	 * 关闭 jdbc 相关连接
	 * 
	 * @param connection connection {@linkplain java.sql.Connection#close()}
	 * @param statement statement {@linkplain java.sql.Statement#close()}
	 * @param resultSet resultSet {@linkplain java.sql.ResultSet#close()}
	 * @param autoCommit 是否需要自动提交
	 * @throws SQLException 关闭异常
	 */
	private void close(Connection connection, Statement statement, ResultSet resultSet, boolean autoCommit)
			throws SQLException {

		if (resultSet != null) {
			// 关闭查询结果集
			resultSet.close();
		}

		if (statement != null) {
			// 关闭 执行
			statement.close();
		}

		if (connection != null && transactionalConnection == null) {
			// 关闭数据库连接
			connection.setAutoCommit(autoCommit);
			connection.close();
		}
	}

	/**
	 * 销毁对象
	 */
	public void destroy() {
		dataSource = null;
		try {
			close();
		} catch (SQLException e) {
			// 销毁 事务 连接异常
			LOGGER.error(" destory jdbc Operation error!", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取事务连接
	 * 
	 * @return {@linkplain java.sql.Connection}
	 */
	public Connection getTransactionalConnection() {
		return transactionalConnection;
	}

	/**
	 * 设置事务连接
	 * 
	 * @param transactionalConnection {@linkplain java.sql.Connection}
	 */
	public void setTransactionalConnection(Connection transactionalConnection) {
		this.transactionalConnection = transactionalConnection;
	}

}
